#!/usr/bin/env python
# encoding: utf-8

import requests
import logging

HOST= 'http://freegirlweb.net/api{}'
STAR_LIST_API = '/stars'
IMAGE_STORE_API = '/image'
URL_CHECK_API = '/black_list'


class HttpService(object):
    """http client to make requests with server."""
    def __init__(self):
        logging.basicConfig()
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)

    def get_stars(self):
        """ Get stars list form server."""
        r = requests.get(HOST.format(STAR_LIST_API))
        if r.status_code == 200:
            star_dict = r.json()
            return star_dict['data']
        else:
            self.logger.error('error to get stars from server.')

    def store_image(self, filename, user_id):
        """Store filename and user_id to server db"""
        data = {'id': user_id, 'name': filename}
        r = requests.post(HOST.format(IMAGE_STORE_API), data=data)

        if r.status_code == 200:
            self.logger.info('success store image %s, user %d' %
                    (filename, user_id))
        else:
            self.logger.error('failed to store image %s, user %d' %
                    (filename, user_id))

    def check_black_url(self, url):
        """Check if `url` is in the black list so that we could skip it."""
        data = {'url_list': url}
        r = requests.post(HOST.format(URL_CHECK_API), data)

        if r.status_code == 200:
            ret_data = r.json()['data']
            if len(ret_data) == 0:
                return False
            else:
                self.logger.info('pass url %s' % url)
                return True
        else:
            self.logger.error('error to check black url %s' % url)
            return False






